<?php

namespace Common\Bundle\LibraryBundle\Controller;

use Common\Bundle\LibraryBundle\Entity\Niveau;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Common\Bundle\LibraryBundle\Form\NiveauType;

/**
 * @Route("/niveau")
 */
class NiveauController extends Controller{

    /**
     * @Route("/", options={"expose"=true})
     * @Template()
     */
    public function indexAction()
    {
        $niveaux = $this->getNiveauRepository()->findAll();
        return array("niveaux" => $niveaux);
    }

    /**
     * @Route("/new", options={"expose"=true}, defaults={"idNiveau"=null})
     * @Route("/{idNiveau}/edit", options={"expose"=true})
     * @Template()
     */
    public function editAction($idNiveau)
    {
        if ($idNiveau === null) {
            $niveau = new Niveau();
        } else {
            $niveau = $this->getNiveauRepository()->find($idNiveau);
        }

        if (!$niveau) {
            throw $this->createNotFoundException();
        }

        $form = $this->createForm(new NiveauType(), $niveau);

        if ($this->getRequest()->isMethod("post")) {
            $form->bind($this->getRequest());
            if ($form->isValid()) {
                $niveau->setIntitule(ucfirst(mb_strtolower(trim($niveau->getIntitule()), "utf-8")));
                $this->getDoctrine()->getManager()->persist($niveau);
                $this->getDoctrine()->getManager()->flush();
                if($idNiveau){
                    $this->get('session')->getFlashBag()->add('success', 'Niveau modifié');
                }
                else
                {
                    $this->get('session')->getFlashBag()->add('success', 'Niveau ajouté');
                }
                return $this->redirect($this->generateUrl("common_library_niveau_index", array()));
            }
        }

        return $this->render('CommonLibraryBundle:Niveau:edit.html.twig', array(
            'form' => $form->createView(),
            'idNiveau' => $idNiveau
        ));
    }

    /**
     * @Route("/{idNiveau}/delete", options={"expose"=true})
     */
    public function deleteAction($idNiveau)
    {
        $niveau = $this->getNiveauRepository()->find($idNiveau);
        $em = $this->getDoctrine()->getManager();

        $em->remove($niveau);
        $em->flush();
        $this->get('session')->getFlashBag()->add('success', 'Niveau supprimé');
        return $this->redirect($this->generateUrl("common_library_niveau_index", array()));

    }


    /**
     * @return \Common\Bundle\LibraryBundle\Entity\Repository\NiveauRepository
     */
    protected function getNiveauRepository() {
        return $this->getDoctrine()->getRepository('CommonLibraryBundle:Niveau');
    }

} 